﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="计划盘点时间：" prop="stockDates">
                        <el-date-picker v-model="queryList.stockDates" type="datetimerange"  style="width: 100%"
                            value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="120px" label="盘点仓库：">
                            <el-select placeholder="---请选择仓库---" v-model="entityObj.warehouseId" style="width: 100%" @change="onWarehouseChange">
                                <el-option label="---请选择仓库---" value="" />
                                <el-option v-for="item in optionsWarehouse" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
                            </el-select>
                        </el-form-item>
                </el-col>
            </el-row>
            <el-row>
               
               
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="物料清单：" >
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="物料编号" label-width="80px">
                                <el-input
                                    placeholder="---请输入编号---"
                                    v-model="queryList.materialCode"
                                    style="width: 150px"
                                />
                            </el-form-item>
                            <el-form-item label="物料分类" label-width="100px">
                                <el-tree-select v-model="queryList.materialTypeIds"
                                    placeholder="---请选择物料分类---"
                                    collapse-tags
                                    collapse-tags-tooltip
                                    :props="{ label: 'label', value: 'value', children: 'children' }" :data="materialTypeTree"
                                    multiple :render-after-expand="false" show-checkbox style="width: 200px" />
                            </el-form-item>
                            <el-form-item label="物料名称" label-width="80px">
                                <el-input
                                    placeholder="---请输入名称---"
                                    v-model="queryList.materialName"
                                    style="width: 200px"
                                />
                            </el-form-item>
                           
                            <el-button
                                :icon="Search"
                                 
                                type="primary"
                                @click="handleSearch"
                            >查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form-item label="过滤条件" label-width="80px">
                                <el-checkbox label="过滤零库存物料" v-model="queryList.isStock"/>
                                <el-checkbox label="过滤无出入库物料" v-model="queryList.isInOrOutStock"/>
                                <el-checkbox label="过滤已禁用物料" v-model="queryList.isMaterialDisable"/>
                            </el-form-item>
                            <el-form inline label-width="49px" style="margin-top: 5px">
                            
                            </el-form>
                        </el-form>
                        <scTable 
                          ref="mytable" 
                          :queryType="'warehouse-stock/stock_pages'" 
                          :queryList="queryList"
                          style="width: 100%;height:350px" 
                          @selection-change="selectionChange">
                            <el-table-column type="selection" width="50" fixed="left" ></el-table-column>
                            <el-table-column prop="materialCode" label="物料编码" width="100" />
                            <el-table-column prop="materialTypeName" label="物料分类" width="140" />
                            <el-table-column prop="materialName" label="物料名称" >
                                <template #default="scope">
                                        <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                                        </div>
                                    </template>
                            </el-table-column>
                            <el-table-column prop="materialSpecs" label="规格" width="180" />
                            <el-table-column prop="unitName" label="单位" width="120" />
                            <el-table-column prop="startStockQty" label="起始库存" width="120" />
                            <el-table-column prop="endStockQty" label="截止库存" width="120" />
                        </scTable>
                    </el-form-item>
                </el-col>
               
            </el-row>
           
        </el-form>
        <template #footer>
            <div style="margin-top: 30px;"></div>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'Show'"
                type="primary"
                :loading="isSaveing"
                @click="opExport()"
            >确定导出盘点模版</el-button>
        </template>
         <!-- 预览组件 -->
		  <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />
    </full-screen-dialog>
</template>

<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "盘点模版下载",
                Edit: "盘点模版下载",
                Show: "盘点模版下载",
            },
            entityObj: {
                status: 1,
            },
            queryList:{
                materialCode:"",
                materialName:"",
                
            },
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                stockDate: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写盘点时间",
                    },
                ],
                createName:[
                    {
                        required: true,
                        type: "string",
                        message: "请填写创建人",
                    },
                ],
               
               
            },
            selectionRows: [],
            selectedObj:{},
            optionsWarehouse: [],
            materialTypeTree: [],
            warehouseName:"",
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //仓库变化
        async onWarehouseChange(val)
        {
            this.selectedObj=this.optionsWarehouse.filter((p)=>p.warehouseId==val)[0];
            console.log("仓库值",this.selectedObj);
            this.queryList.warehouseId=val;
            this.warehouseName=this.selectedObj.warehouseName
            this.$refs.mytable.getData();
            
        },
        handleSearch() {
            if(!this.queryList.warehouseId)
            {
                this.$message.error('请先选择仓库')
            }else
            {
                this.$refs.mytable.getData();
            }
            
        },
        resetSearch(){
            this.queryList.materialCode='';
            this.queryList.materialName='';
        },
         //表格选择后回调事件
         selectionChange(selection) {
            this.selectionRows = selection;
        },
        //导出
        async opExport(){
				try {
                    if (this.selectionRows.length > 0) {
                        await this.$API.auth.PostDownApi.post(`stockOrder/export`,
						    {   
                                stockDates:this.queryList.stockDates,
                                warehouseId:this.queryList.warehouseId,
                                warehouseName:this.warehouseName,
                                exportList: this.selectionRows 
                            },
                        ).then((res)=>{
                            console.log("res",res)
                            var fileName="";
                            this.getFileName(fileName,res)
                            console.log("fileName",fileName)

                            this.downloadfile(res.data);
                        }).catch((err) => {
                            this.$message.error('下载错误：获取文件流错误')
                        });
                    }else {
                        this.$message.error("请选择要导出的数据");
                    }
				} catch (error) {
					this.loading = false;
					return false;
				}
        },
        getFileName(fileName, response) {
            // 需要响应设置此header暴露给外部，才能获取到
            let contentDisposition = response.headers['content-disposition']
            if (contentDisposition) {
                // 正则获取filename的值
                let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
                let matches = filenameRegex.exec(contentDisposition)
                if (matches != null && matches[1]) {
                    fileName = matches[1].replace(/['"]/g, '')
                }
                // 通过 URLEncoder.encode(pFileName, StandardCharsets.UTF_8.name()) 加密编码的, 使用decodeURI(fileName) 解密
                fileName = decodeURI(fileName)
                // 通过 new String(pFileName.getBytes(), StandardCharsets.ISO_8859_1) 加密编码的, 使用decodeURI(escape(fileName)) 解密
                // fileName = decodeURI(escape(fileName))
            }
            return fileName
        },

        downloadfile(blob) {
                var nowDate = new Date();
                var latestYear = nowDate.getFullYear();//当前年份
                var latestMonth = nowDate.getMonth() + 1;//当前月份
                var latestDay = new Date().getDate();//当前号数
                var nowDateFormat = latestYear + '-' + latestMonth + '-' + latestDay;
                var fileName=nowDateFormat+"."+this.selectedObj.warehouseName+".物料盘点.xlsx";
				
				let fileReader = new FileReader()
				//var blob = new Blob([res], {type: 'application/octet-stream;charset=UTF-8'})
				fileReader.onload = function () 
				{
				try {
					var downloadElement = document.createElement('a')
					var href = window.URL.createObjectURL(blob) // 创建下载的链接
					downloadElement.style.display = 'none'
					downloadElement.href = href
					downloadElement.download = decodeURI(fileName) // 下载后文件名
					document.body.appendChild(downloadElement)
					downloadElement.click() // 点击下载
					document.body.removeChild(downloadElement) // 下载完成移除元素
					window.URL.revokeObjectURL(href)
				} catch (err) {}
				}
				fileReader.readAsText(blob)
		},
      
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post("warehouse/list",{IsExternal:false});
                if (returnValue.status == 200) {
                    console.log("仓库",returnValue.response);
                    this.optionsWarehouse = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = {
                ...data
            }; 
        },
         //图片预览
			 handlePreview(row) {
				if (!row.materialImages || row.materialImages.length == 0) {
					return;
				}
				this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
				this.srcList = row.materialImages; // 设置预览列表
				this.showImage = true; // 显示 el-image

			},
			closeViewer(){
				this.showImage = false; 
			},
        
    },
    async mounted() {
        await this.initOptions();
        if(this.mode=='Add'){
            this.entityObj.createName = tool.data.get("USER_INFO").Name;
            this.entityObj.stockDate = tool.formatDate(new Date());
        }
        try {
				const returnValue = await this.$API.auth.PostProcessApi.post("material-type/tree", {
					status: 1
				});
				if (returnValue.status == 200) {
					this.materialTypeTree = returnValue.response;
				} else {
					this.$message.error("操作失败:" + returnValue.msg);
				}
			} catch (error) {}
    },
};
</script>

<style></style>
